﻿/*
 * CHttpService.cpp
 *
 *  Created on: 2018年1月8日
 *      Author: terry
 */

#include "CHttpService.h"
#include "HttpFactory.h"
#include "Path.h"
#include "AppConst.h"

#include "DateTime.h"
#include "TimeUtil.h"

#include "TStringUtil.h"
#include "Version.h"
#include "AppConfig.h"

#include "Application.h"
#include "DbHttpUserStore.h"
#include "DbJsonConnection.h"
#include "JsonUtil.h"
#include "JsonCast.h"

#include "SqlCondition.h"
#include "TFileUtil.h"
#include "TSafeStr.h"

#include "DbStore.h"
#include "TimeUtil.h"

#include "Socket.h"
#include "HttpServiceUtil.h"
#include "HttpFactory.h"
#include "BasicMacro.h"


CHttpService::CHttpService():
    m_server(HttpFactory::createServer(), HttpFactory::destroyServer),
	m_port()
{
	setupUri();

}

CHttpService::~CHttpService()
{
    stop();
}

void CHttpService::setDb(std::shared_ptr< db::DbConnectionPool >& dbPool)
{
	m_dbPool = dbPool;

	std::shared_ptr< DbHttpUserStore > store(new DbHttpUserStore(dbPool));

    setUserStore(HttpUserStorePtr(store));
}

bool CHttpService::start(int port)
{
    if (isStarted())
    {
        stop();
    }

	m_port = port;


    std::string webrootPath = getWebsitePath();
    m_server->setWebRoot(webrootPath.c_str());
    m_server->setUserFile(NULL);


	std::string logPath = getLogPath();
	m_server->addDir("/log", logPath.c_str());


	m_server->addApi("/api");
	m_server->addApi("/system");

    return m_server->start("0.0.0.0", port, this);
}

void CHttpService::stop()
{
    m_server->stop();
}

bool CHttpService::isStarted()
{
    return m_server->isStarted();
}

void CHttpService::broadcast(const char *data, size_t len)
{
    m_server->broadcast(HttpServer::WS_TEXT, (char*)data, len);
}

void CHttpService::broadcast(const std::string& data)
{
	m_server->broadcast(HttpServer::WS_TEXT, data.c_str(), data.size());
}

int CHttpService::getPort()
{
    return m_port;
}

void CHttpService::setupUri()
{
	route("/api/device/gps", &CHttpService::listDeviceGps, this);
	route("/api/device/status", &CHttpService::listDeviceStatus, this);
}


std::string CHttpService::getWebsitePath()
{
	std::string dir = Application::instance()->getAppDir();
	std::string fullpath = comn::Path::join(dir, "webroot");
	if (!comn::Path::exist(fullpath))
	{
		fullpath = "webroot";
	}
	return fullpath;
}

std::string CHttpService::getLogPath()
{
	std::string dir = AppConst::getAppDir();
	std::string fullpath = comn::Path::join(dir, "log");
	return fullpath;
}

int CHttpService::listDeviceGps(HttpRequest& request, HttpResult& result)
{
	Json::Value json(Json::arrayValue);

	db::DbJsonConnection connection(*m_dbPool);

	db::JsonList jsonList;

	std::string sql = "select dev as UserID, name as UserName, longitude as Longitude, latitude as Latitude, num from DeviceNumber;";
	if (connection.query(sql, jsonList))
	{
		int64_t curTime = time(nullptr);
		for (Json::Value& item : jsonList)
		{
			item["Time"] = curTime;
		}

		connection.toJson(jsonList, json);
	}
	else
	{
		//
	}

	return setResult(result, json);
}

int CHttpService::listDeviceStatus(HttpRequest& request, HttpResult& result)
{
	Json::Value json(Json::arrayValue);

	db::DbJsonConnection connection(*m_dbPool);

	db::JsonList jsonList;

	std::string sql = "select dev as yonghuid, name as yonghuname, status as yonghuzxbj, num, fatherid as UnitId from DeviceNumber;";
	if (connection.query(sql, jsonList))
	{
		connection.toJson(jsonList, json);
	}
	else
	{
		//
	}

	return setResult(result, json);
}
